<template>
	<mu-container>
		<mu-form ref="form" :model="validateForm" class="mu-demo-form">
			<mu-form-item label="用户名" prop="username" :rules="usernameRules">
				<mu-text-field v-model="validateForm.username" prop="username"></mu-text-field>
			</mu-form-item>
			<mu-form-item label="密码" prop="password" :rules="passwordRules">
				<mu-text-field type="password" v-model="validateForm.password" prop="password"></mu-text-field>
			</mu-form-item>
			<mu-form-item>
				<mu-button color="primary" @click="submit">登录</mu-button>
				<mu-button @click="clear">重置</mu-button>
			</mu-form-item>
		</mu-form>
	</mu-container>

</template>

<script>
	export default {
		data() {
			return {
				usernameRules: [{
						validate: (val) => !!val,
						message: '必须填写用户名'
					},
					{
						validate: (val) => val.length >= 3,
						message: '用户名长度大于3'
					}
				],
				passwordRules: [{
						validate: (val) => !!val,
						message: '必须填写密码'
					},
					{
						validate: (val) => val.length >= 3 && val.length <= 16,
						message: '密码长度大于3小于16'
					}
				],
				validateForm: {
					username: '',
					password: '',
				}
			}
		},
		methods: {
			submit() {
				this.$refs.form.validate().then((result) => {
					console.log('form valid: ', result)
					if(result){
						this.login();
					}
				});
			},
			clear() {
				this.$refs.form.clear();
				this.validateForm = {
					username: '',
					password: '',
					isAgree: false
				};
			},
			//登录
			login() {
				
				//获取值
				let self = this;
				var username = this.validateForm.username;
				var password = this.validateForm.password;
				
				var querystring = require("querystring");
				var params = querystring.stringify({
					userName: username,
					password: password
				});
				self.$ajax({
						method: "post",
						url: "/login",
						data: params
					})
					.then(function (res) {
						if (res.data.code == 200) {
							self.clear();
							localStorage.setItem('user',JSON.stringify( res.data.data));
							var name = self.$route.query.redirect || 'Bookkeeping';
							self.$toast.success('登录成功');
							//获取登录成功后要跳转的路由。
							self.$router.push({
								name: name
							});
						} else {
							self.clear();
							self.$toast.error(res.data.content);
							
						}
					})
					.catch(function (err) {
						console.log(err);
						self.clear();
						
					});
			},
		}
	};
</script>
<style>
	.mu-demo-form {
		width: 100%;
		max-width: 460px;
	}
</style>
